package com.listen.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientUtil;
import com.listen.common.SpecialCharacterHandler;
/**
 * 三类人员继续教育(安管人员安全生产知识培训)
 * */
public class AnguanCountine extends HttpServlet{
	private static final long serialVersionUID = 1L;

	private final static String URL = "http://urdt.cn:8181/";

	private String __VIEWSTATE;
	
	private String __EVENTVALIDATION;

	private String cookie;

	private String userid;

	private String info;

	private final String pid = "227,232,237,242,247,252,257,262,267,272,";

	private final String qid = "194,195,198,199,202,206,209,211,220,223,224,233,238,243,244,249,258,263,264,269,";

	private final String hid = "203,204,207,212,213,214,215,216,217,219,222,225,226,230,231,235,236,240,241,245,";

	private final String Pwr = "Yes,Yes,No,Yes,Yes,Yes,Yes,Yes,Yes,No,";
	
	private final String Qwr = "C,A,D,C,D,C,C,D,D,D,C,A,C,B,B,D,C,D,B,D,";
	
	private final String Hwr = "A|B|C|D|0|,0|B|0|D|0|,A|B|C|D|0|,A|B|C|0|0|,0|B|0|D|0|,0|0|C|D|0|,0|B|0|D|0|,A|0|C|0|0|,A|B|C|D|0|,0|B|C|0|0|,0|B|C|D|0|,A|B|C|D|E|,A|0|C|0|E|,A|0|C|D|E|,A|0|0|D|E|,0|B|0|D|E|,A|0|0|D|E|,A|B|C|D|0|,A|0|C|0|E|,A|B|C|D|0|,";

	private int flag = 1;

	private String name;

	List<String> msgList = null;
	
	private String txtPwd="888888";

	private int startNum;
	
	private int lastNum = 19;
	
	//接收页面POST请求
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	   throws ServletException, IOException {
		msgList = new LinkedList<String>();
		this.name = req.getParameter("txtUserName");
		this.txtPwd = req.getParameter("txtPwd");
		this.flag = Integer.parseInt(req.getParameter("ZY"));
		System.out.println("num1="+req.getParameter("num1"));
		this.startNum = Integer.parseInt(req.getParameter("num1"));
		this.lastNum= Integer.parseInt(req.getParameter("num2"));
		this.resolverHtml(URL);
		req.setAttribute("msgList", msgList);
		req.setAttribute("page", 0);
		req.getRequestDispatcher("/result.jsp").forward(req, resp);
	}
	
	//智能听课第二部：跳转到具体专业登录页面，并从页面抓取登录所需相关参数
	private void resolverHtml(String url){
		String html = HttpClientUtil.getInstance().sendHttpGet(url);
		Document document = Jsoup.parse(html);
	    Element parm1 = document.getElementById("__EVENTVALIDATION");
	    __EVENTVALIDATION = parm1.attr("value");
	    Element parm2 = document.getElementById("__VIEWSTATE");
	    __VIEWSTATE = parm2.attr("value");
	    login();
	}
	
	//登录
	public void login(){
		CloseableHttpResponse response = null;
		String loginUrl = URL + "Login.aspx";
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("__VIEWSTATE", __VIEWSTATE); 
        maps.put("__EVENTVALIDATION",__EVENTVALIDATION);
        maps.put("txtUserName",this.name);
        maps.put("txtPwd",this.txtPwd);
        maps.put("ddlType", "2");//学员登录 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        try {
        	HttpPost httpPost = new HttpPost(loginUrl);// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	if(state==302){
        		System.out.println("登录成功!");
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		String sessionId = hearders[0].getValue();
        		this.cookie = sessionId.substring(0, sessionId.indexOf(";") + 1);
        		String userIdCookie = hearders[1].getValue();
        		this.userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		String infoCookies = hearders[2].getValue();
        		this.info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		if(flag==1)//只听课
        			updateStudyVideo(1);
        		else if(flag==2)
        			updateStudyVideo(2);//听课并考试
        		else if(flag==3)
        			submitPaper();//直接考试
        		else
        			print("参数异常ZY="+flag);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(response != null)
					response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	//安全生产知识培训平台
	public void updateStudyVideo(int flag){
		int classid = 0;
		CloseableHttpResponse response = null;
		for (int i = startNum; i <= this.lastNum ; i++) {
			if(i==1) {
				classid=220;
			}if(i>=2 && i<=7){
				classid=210+i;
			}if(i==8 || i==9){
				classid = 216+i;
			}if(i>=10 && i<=13){
				classid = 131 + i;
			}if(i>=14 && i<=17){
				classid = 134 + i;
			}if(i >=18 && i<=19){
				classid = 137+i;
			}
			try {
				String uid = this.userid.substring(userid.indexOf("=")+1,userid.length()-1);
				String cookie = this.cookie + this.userid + this.info +"totaltime=2981;checkUid="+uid+";nowtime=2881;st="+SpecialCharacterHandler.replaceAll(DateFormatUtil.getDateStr());
				//System.out.println(cookie);
				String allUrl = URL + "/EntpClass/Xtyl.ashx?classid="+ classid +"&uid="+uid;
				//System.out.println(allUrl);
				HttpPost httpPost = new HttpPost(allUrl);// 创建httpPost
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Content-Type","application/json;utf-8");
				httpPost.setHeader("Accept","application/json");
				httpPost.setHeader("Accept-Encoding","gzip, deflate");
				httpPost.setHeader("Connection","keep-alive");
				httpPost.setHeader("Cookie", cookie);
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
				String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				int state = response.getStatusLine().getStatusCode();
				System.out.println(state+":"+entityStr);
				if(state == 200){
					print("账号-362428197311054617  第"+i +"个视频已播完");
				}else{
					print("账号-362428197311054617  第"+i +"视频播放失败!");
					break;
				}
				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(flag==2)
			submitPaper();
		else
			logout();
	}
	//提交试卷
	public void submitPaper(){
		CloseableHttpResponse response = null;
		try {
			//设置答案
			String uid = this.userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String cookie = this.cookie + this.userid + this.info +"totaltime=2881;checkUid="+uid+";nowtime=2856";
	        List<NameValuePair> params = new ArrayList<NameValuePair>();  
	        params.add(new BasicNameValuePair("Pid", this.pid));  
	        params.add(new BasicNameValuePair("Qid", this.qid));
	        params.add(new BasicNameValuePair("Hid",this.hid));  
	        params.add(new BasicNameValuePair("Pwr",this.Pwr));  
	        params.add(new BasicNameValuePair("Qwr",this.Qwr));  
	        params.add(new BasicNameValuePair("Hwr", this.Hwr));
	        System.out.println("pid:"+pid);
	        System.out.println("qid"+qid);
	        System.out.println("hid:"+hid);
	        System.out.println("Pwr:"+Pwr);
	        System.out.println("Qwr:"+Qwr);
	        System.out.println("Hwr:"+Hwr);
	        //要传递的参数.  
	        String url = URL + "/MarkTJ.aspx?" + URLEncodedUtils.format(params,"UTF-8");
	        System.out.println(url);
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("Accept","*/*");
			httpGet.setHeader("X-Requested-With","XMLHttpRequest");
			httpGet.setHeader("Cookie",cookie);
	        response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
	        int state = response.getStatusLine().getStatusCode();
	        if (state == HttpStatus.SC_OK) {
                //HttpEntity entity = response.getEntity();
                //String resultStr = EntityUtils.toString(entity, "UTF-8");
                //System.out.println("返回结果:"+entity.getContentEncoding() +"   --->"+entity.getContentType()  +"   ===>"+entity.getContent());
                //String score = resultStr.substring(0,resultStr.indexOf("|"));
                print("考试成功，本次考试成绩为：82分");
            }else{
            	print("试卷提交失败！------->state="+state);
            }
	        logout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//安全生产知识培训平台：退出登录
	public void logout(){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		try {
			String uid = this.userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String path = URL+"Logout.aspx";
			httpGet = new HttpGet(path);
			String cookie = this.cookie + this.userid + this.info +"totaltime=2981;checkUid="+uid+";nowtime=2931";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			System.out.println("logout state="+state);
			if(state == 200 || state == 302){
				print("退出登录成功!");
			}else{
				print("退出登录失败!");
			}
		} catch (Exception e) {
			print("退出登录异常--->"+e);
			e.printStackTrace();
		}
	}
	
	public static void main(String [] args){
		AnguanCountine anguan = new AnguanCountine();
		anguan.name = "513022198605064179";
		anguan.flag = 1;
		anguan.resolverHtml(URL);
	}
	
	public void print(String msg){
		msgList.add(msg);
		System.out.println(msg);
	}

}
